/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.workflow.service.button;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.je.bpm.core.model.config.process.ProcessBasicConfigImpl;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.impl.cmd.SubmitTypeEnum;
import com.je.bpm.engine.impl.identity.Authentication;
import com.je.bpm.model.process.model.ProcessRunForm;
import com.je.bpm.model.process.results.ProcessButtonListResult;
import com.je.bpm.runtime.process.ProcessOperatorService;
import com.je.bpm.runtime.process.operator.ProcessEmptySponsorOperator;
import com.je.bpm.runtime.process.operator.ProcessEmptyStartOperator;
import com.je.bpm.runtime.shared.OperatorSharedService;
import com.je.bpm.runtime.shared.RemoteCallServeManager;
import com.je.bpm.runtime.shared.operator.Operator;
import com.je.bpm.runtime.shared.operator.OperatorRegistry;
import com.je.bpm.runtime.shared.operator.desc.OperationParamDesc;
import com.je.bpm.runtime.shared.operator.validator.PayloadValidErrorException;
import com.je.common.auth.impl.account.Account;
import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.Condition;
import com.je.common.base.mapper.query.ConditionEnum;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaRbacService;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.service.QueryBuilderServiceImpl;
import com.je.servicecomb.RpcSchemaFactory;
import com.je.workflow.config.UpcomingPullConfig;
import com.je.workflow.model.TaskCandidateDTO;
import com.je.workflow.rpc.workflow.TaskCandidateRpcCallBackService;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Consumer;

import static com.je.common.base.util.StringUtil.getStringParameter;
import static com.je.workflow.service.user.ResultUserParserImpl.RANDOM_TEAM_ID;

@Service
public class ButtonServiceImpl implements ButtonService {

    private static final Logger logger = LoggerFactory.getLogger(ButtonServiceImpl.class);

    @Autowired
    private MetaService metaService;
    @Autowired
    private ProcessOperatorService processOperatorService;
    @Autowired
    private OperatorSharedService operatorSharedService;
    @Autowired
    private RemoteCallServeManager remoteCallServeManager;
    @Autowired
    private CommonService commonService;
    @Autowired
    private MetaRbacService metaRbacService;
    @Autowired
    protected QueryBuilderServiceImpl queryBuilderService;

    @Override
    public List<Map<String, Object>> getButtons(String prod, String tableCode, String funcCode, String beanId) {
        try {
            ProcessButtonListResult processButtonListResult = processOperatorService.getButton(funcCode, getLogUserId(), beanId,
                    getBean(prod, beanId, tableCode));
            List<ProcessRunForm> entity = processButtonListResult.getEntity();
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (ProcessRunForm processRunForm : entity) {
                Map<String, Object> runFormConfig = new HashMap<>();
                runFormConfig.put("formConfig", processRunForm.getFromConfig());
                runFormConfig.put("buttonList", processRunForm.getList());
                runFormConfig.put("workflowConfig", processRunForm.getWorkFlowConfig());
                resultList.add(runFormConfig);
            }
            return resultList;
        } catch (PayloadValidErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Map<String, Object> getBean(String prod, String beanId, String tableCode) {
        Object dynaBeanObject = remoteCallServeManager.doGet(prod, beanId, tableCode, null);
        if (dynaBeanObject == null) {
            throw new ActivitiException("获取bean信息异常！");
        }
        Map<String, Object> map = (Map<String, Object>) dynaBeanObject;
        return (Map<String, Object>) map.get("values");
    }

    @Override
    public List<String> getParams(String operationId) {
        OperationParamDesc paramDesc = operatorSharedService.getOperatorParams(operationId);
        return paramDesc.getParamKeys();
    }

    @Override
    public Map<String, Object> operate(String operationId, String prod, String funcCode, String pdid,
                                       String beanId, String tableCode, String funcId, Map<String, Object> operationCustomerParam) {
        Map<String, Object> result = new HashedMap();
        if (Strings.isNullOrEmpty(operationId)) {
            throw new ActivitiException("操作id为空！");
        }
        Operator operator = OperatorRegistry.get(operationId);
        Map<String, Object> bean = getBean(prod, beanId, tableCode);
        Map<String, Object> map = new HashMap<>();
        map.put("pdid", pdid);
        map.put("funcCode", funcCode);
        map.put("prod", prod);
        map.put("bean", bean);
        map.put("beanId", beanId);
        map.put("tableCode", tableCode);
        putOperationCustomerParam(map, operationCustomerParam);
        DynaBean exigencyBean = null;
        if (operator instanceof ProcessEmptySponsorOperator || operator instanceof ProcessEmptyStartOperator) {
            if (operationCustomerParam.get("exigency") != null && !Strings.isNullOrEmpty(String.valueOf(operationCustomerParam.get("exigency")))) {
                metaService.delete("JE_WORKFLOW_EXIGENCY", ConditionsWrapper.builder().eq("EXIGENCY_PKVALUE", beanId));
                String exigency = (String) operationCustomerParam.get("exigency");
                exigencyBean = new DynaBean("JE_WORKFLOW_EXIGENCY", true);
                exigencyBean.setStr("EXIGENCY_TYPE", exigency);
                exigencyBean.set("EXIGENCY_PKVALUE", beanId);
                metaService.insert(exigencyBean);
            }
        }

        try {
            operator.operate(map);
        } catch (PayloadValidErrorException e) {
            e.printStackTrace();
        }
        bean = getBean(prod, beanId, tableCode);
        if (Strings.isNullOrEmpty(funcId)) {
            DynaBean process = metaService.selectOne("JE_WORKFLOW_PROCESSINFO",
                    ConditionsWrapper.builder().eq("PROCESSINFO_KEY", pdid.split(":")[0]));
            funcId = process.getStr("PROCESSINFO_FUNC_ID");
        }
        updateBusinessWorkFlowInfo(bean, beanId, prod, tableCode, funcCode, funcId);
        if (exigencyBean != null) {
            exigencyBean.set("EXIGENCY_PIID", bean.get("SY_PIID"));
            metaService.update(exigencyBean);
        }
        remotePush(bean, beanId, tableCode, funcCode);
        if (!Strings.isNullOrEmpty(funcCode)) {
            result.put("processInfo", getButtons(prod, tableCode, funcCode, beanId));
            result.put("bean", getBean(prod, beanId, tableCode));
            return result;
        } else {
            return null;
        }
    }

    /**
     * 修改bean信息，往业务数据中更新流程信息
     */
    private void updateBusinessWorkFlowInfo(Map<String, Object> bean, String beanId, String prod, String tableCode, String funcCode, String funcId) {
        buildRuTaskFields(bean, beanId);
        ProcessBasicConfigImpl processBasicConfig = new ProcessBasicConfigImpl();
        processBasicConfig.setTableCode(tableCode);
        processBasicConfig.setFuncCode(funcCode);
        processBasicConfig.setFuncId(funcId);
        remoteCallServeManager.doUpdate(bean, beanId, processBasicConfig, prod, null);
    }

    /**
     * 远程推送待办信息
     *
     * @param bean
     * @param beanId
     * @param tableCode
     */
    private void remotePush(Map<String, Object> bean, String beanId, String tableCode, String funcCode) {
        if (!UpcomingPullConfig.isPull()) {
            return;
        }
        String prod = UpcomingPullConfig.getProdName();
        String serviceName = UpcomingPullConfig.getServiceName();
        if (Strings.isNullOrEmpty(prod) || Strings.isNullOrEmpty(serviceName)) {
            return;
        }
        TaskCandidateDTO taskCandidateDTO = TaskCandidateDTO.build(bean, tableCode, beanId, funcCode);
        if (bean.get("SY_PDID") == null) {
            return;
        }
        String pdid = (String) bean.get("SY_PDID");
        if (Strings.isNullOrEmpty(pdid)) {
            return;
        }
        String processKey = pdid.split(":")[0];
        DynaBean dynaBean = metaService.selectOne("JE_WORKFLOW_PROCESSINFO", ConditionsWrapper.builder().eq("PROCESSINFO_KEY", processKey));
        taskCandidateDTO.setProcessTypeCode(dynaBean.getStr("PROCESSINFO_TYPE_CODE"));
        taskCandidateDTO.setProcessTypeName(dynaBean.getStr("PROCESSINFO_TYPE_NAME"));
        taskCandidateDTO.setProcessKey(dynaBean.getStr("PROCESSINFO_KEY"));
        taskCandidateDTO.setProcessName(dynaBean.getStr("PROCESSINFO_NAME"));
        TaskCandidateRpcCallBackService taskCandidateRpcCallBackService = RpcSchemaFactory.getRemoteProvierClazz(prod, serviceName,
                TaskCandidateRpcCallBackService.class);
        taskCandidateRpcCallBackService.invoke(taskCandidateDTO);
    }

    private void buildRuTaskFields(Map<String, Object> bean, String beanId) {
        List<DynaBean> checkList = metaService.select("JE_WORKFLOW_V_RN_TASK",
                ConditionsWrapper.builder().eq("BUSINESS_KEY", beanId)
                        .orderByAsc("SY_CREATETIME"));
        if (checkList.size() == 0) {
            buildHiBeanTaskInfo(bean, beanId);
            return;
        }
        //过滤传阅人，不要把传阅的人放到待审批人里面
        List<Condition> conditions = new ArrayList<>();
        conditions.add(buildCondition("TASK_CIRCULATION", "1"));
        Condition condition = new Condition();
        condition.setCn("or");
        condition.setCode("TASK_CIRCULATION");
        condition.setType(ConditionEnum.IS_NULL.getType());
        conditions.add(condition);
        Consumer<ConditionsWrapper> tConsumer = i -> {
            for (Condition c : conditions) {
                queryBuilderService.condition(i, c, null);
            }
        };
        List<DynaBean> list = metaService.select("JE_WORKFLOW_V_RN_TASK",
                ConditionsWrapper.builder().eq("BUSINESS_KEY", beanId)
                        .and(tConsumer)
                        .orderByAsc("SY_CREATETIME"));
        Set<String> currentNodeNames = new HashSet<>();
        Set<String> currentNodeKeys = new HashSet<>();
        Set<String> assigneeNames = new HashSet<>();
        Set<String> assigneeIds = new HashSet<>();
        Set<String> hiAssigneeNames = new HashSet<>();
        Set<String> hiAssigneeIds = new HashSet<>();
        String submitUserName = "";
        String submitUserId = "";
        String lastComment = "";
        String submitTypeCode = "";
        String submitTypeName = "";
        for (DynaBean dynaBean : list) {
            String handle = dynaBean.getStr("TASK_HANDLE");
            if (handle.equals("0")) {
                currentNodeNames.add(dynaBean.getStr("TASK_NODE_NAME"));
                currentNodeKeys.add(dynaBean.getStr("TASK_NODE_ID"));
                assigneeNames.add(dynaBean.getStr("ASSIGNEE_NAME"));
                assigneeIds.add(dynaBean.getStr("ASSIGNEE_ID"));
            } else {
                hiAssigneeNames.add(dynaBean.getStr("ASSIGNEE_NAME"));
                hiAssigneeIds.add(dynaBean.getStr("ASSIGNEE_ID"));
            }
            submitUserName = dynaBean.getStr("EXECUTION_SUBMIT_USER_NAME");
            submitUserId = dynaBean.getStr("EXECUTION_SUBMIET_USER_ID");
            lastComment = dynaBean.getStr("EXECUTION_LAST_COMMENT");
            submitTypeCode = dynaBean.getStr("EXECUTION_SUBMIT_TYPE");
            submitTypeName = SubmitTypeEnum.getNameByType(submitTypeCode);
        }
        hiAssigneeNames.add(submitUserName);
        hiAssigneeIds.add(submitUserId);
        //当前执行节点
        bean.put("SY_CURRENTTASK", String.join(",", currentNodeNames));
        bean.put("SY_CURRENTTASK_KEYS", String.join(",", currentNodeKeys));
        //流程任务指派人
        bean.put("SY_LASTFLOWUSER", submitUserName);
        //流程任务指派人ID
        bean.put("SY_LASTFLOWUSERID", submitUserId);
        //流程最后任务指派信息
        JSONObject lastFlowInfo = new JSONObject();
        lastFlowInfo.put("userName", submitUserName);
        lastFlowInfo.put("userId", submitUserId);
        lastFlowInfo.put("submitTypeName", submitTypeName);
        lastFlowInfo.put("submitTypeCode", submitTypeCode);
        lastFlowInfo.put("comment", lastComment);
        bean.put("SY_LASTFLOWINFO", lastFlowInfo.toJSONString());
        //流程待执行人ID
        bean.put("SY_PREAPPROVUSERS", String.join(",", assigneeIds));
        //流程待执行人
        bean.put("SY_PREAPPROVUSERNAMES", String.join(",", assigneeNames));
        if (bean.get("SY_APPROVEDUSERS") != null && !Strings.isNullOrEmpty((String) bean.get("SY_APPROVEDUSERS"))) {
            hiAssigneeIds.addAll(Arrays.asList(((String) bean.get("SY_APPROVEDUSERS")).split(",")));
            hiAssigneeNames.addAll(Arrays.asList(((String) bean.get("SY_APPROVEDUSERNAMES")).split(",")));
        }
        bean.put("SY_APPROVEDUSERS", String.join(",", hiAssigneeIds));
        bean.put("SY_APPROVEDUSERNAMES", String.join(",", hiAssigneeNames));
    }


    public Condition buildCondition(String code, String value) {
        Condition condition = new Condition();
        condition.setCn("or");
        condition.setCode(code);
        condition.setValue(value);
        condition.setType(ConditionEnum.NE.getType());
        return condition;
    }

    private void buildHiBeanTaskInfo(Map<String, Object> bean, String beanId) {
        List<DynaBean> hiList = metaService.select("JE_WORKFLOW_V_HI_TASK", ConditionsWrapper.builder().eq("BUSINESS_KEY", beanId).orderByAsc("SY_CREATETIME"));
        if (hiList.size() == 0) {
            return;
        }
        DynaBean hiDynaBean = hiList.get(0);
        //流程任务指派人
        bean.put("SY_LASTFLOWUSER", Authentication.getAuthenticatedUser().getName());
        //流程任务指派人ID
        bean.put("SY_LASTFLOWUSERID", Authentication.getAuthenticatedUser().getDeptId());
        //流程最后任务指派信息
        JSONObject lastFlowInfo = new JSONObject();
        lastFlowInfo.put("userName", Authentication.getAuthenticatedUser().getName());
        lastFlowInfo.put("userId", Authentication.getAuthenticatedUser().getDeptId());
        lastFlowInfo.put("submitTypeName", SubmitTypeEnum.getNameByType(hiDynaBean.getStr("EXECUTION_COMMIT_TYPE")));
        lastFlowInfo.put("submitTypeCode", hiDynaBean.getStr("EXECUTION_COMMIT_TYPE"));
        lastFlowInfo.put("comment", hiDynaBean.getStr("EXECUTION_COMMENT"));
        bean.put("SY_LASTFLOWINFO", lastFlowInfo.toJSONString());
        //当前执行节点
        bean.put("SY_CURRENTTASK", "已结束");
        //流程待执行人ID
        bean.put("SY_PREAPPROVUSERS", "");
        //流程待执行人
        bean.put("SY_PREAPPROVUSERNAMES", "");
        if (bean.get("SY_APPROVEDUSERS") != null && bean.get("SY_APPROVEDUSERS").toString().length() > 0
                && bean.get("SY_APPROVEDUSERS").toString().indexOf(Authentication.getAuthenticatedUser().getDeptId()) == -1) {
            bean.put("SY_APPROVEDUSERS", bean.get("SY_APPROVEDUSERS") + "," + Authentication.getAuthenticatedUser().getDeptId());
            bean.put("SY_APPROVEDUSERNAMES", bean.get("SY_APPROVEDUSERNAMES") + "," + Authentication.getAuthenticatedUser().getName());
        } else {
            bean.put("SY_APPROVEDUSERS", Authentication.getAuthenticatedUser().getDeptId());
            bean.put("SY_APPROVEDUSERNAMES", Authentication.getAuthenticatedUser().getName());
        }
    }

    @Override
    public void addCommonUser(String assignee) {
        try {
            JSONArray jsonArray = JSONArray.parseArray(assignee);
            //要添加的人,
            List<String> addList = Lists.newLinkedList();
            Set<String> set = new HashSet<>();
            Map<String, String> addMap = Maps.newLinkedHashMap();
            if (jsonArray == null) {
                return;
            }
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String[] assignees = jsonObject.getString("assignee").split(",");
                String[] assigneeNames = jsonObject.getString("assigneeName").split(",");
                for (int j = 0; j < assignees.length; j++) {
                    addMap.put(assignees[j], assigneeNames[j]);
                    addList.add(assignees[j]);
                }
            }

            //当前登陆人的用户、部门id
            String loginUserId = SecurityUserHolder.getCurrentAccountRealUserId();
            String realOrgId = SecurityUserHolder.getCurrentAccountDepartment().getId();
            //常用中的人
            List<String> commonList = Lists.newLinkedList();
            // 获取常用人中所有的id
            String whereSql = " AND SY_CREATEUSERID = '" + loginUserId + "' AND SY_CREATEORGID = '" + realOrgId + "' ORDER BY COMMONUSER_COUNT DESC,SY_CREATETIME DESC";
            List<DynaBean> dynaBeanList = metaService.select("JE_WORKFLOW_COMMONUSER", ConditionsWrapper.builder().apply(whereSql));
            for (DynaBean bean : dynaBeanList) {
                commonList.add(bean.getStr("COMMONUSER_USER_ID"));
            }
            //要删除的人员id
            LinkedHashSet<String> deleteSetIds = new LinkedHashSet<>(commonList);
            List<String> idSource = new ArrayList<>(deleteSetIds);
            List<String> deleteIdSource = new ArrayList<>(deleteSetIds);
            List<String> existIds = new ArrayList<>();

            //检查人员是否还存在，或者已变更 （删除不存在的人，和超过50的僵尸人）
            List<DynaBean> notExist = metaRbacService.selectByNativeQuery(NativeQuery.build().tableCode("JE_RBAC_VUSERQUERY").in("JE_RBAC_ACCOUNTDEPT_ID", commonList));
            for (DynaBean bean : notExist) {
                existIds.add(bean.getStr("JE_RBAC_ACCOUNTDEPT_ID"));
            }

            if (existIds.size() > 0) {
                deleteIdSource.removeAll(existIds);
                idSource.removeAll(deleteIdSource);
            }
            List<String> strings = idSource.size() > 50 ? idSource.subList(50, idSource.size()) : null;
            idSource = idSource.size() > 50 ? idSource.subList(0, 50) : idSource;
            if (strings != null) {
                deleteIdSource.addAll(strings);
            }
            if (deleteIdSource.size() > 0) {
                metaService.executeSql("delete from JE_WORKFLOW_COMMONUSER where COMMONUSER_USER_ID in ({0})", deleteIdSource);
            }

            //获取相同的人的集合id
            List<String> theSameList = getTheSameSection(idSource, addList, true);
            // 给相同人的数量加1
            metaService.executeSql(" UPDATE JE_WORKFLOW_COMMONUSER SET COMMONUSER_COUNT = COMMONUSER_COUNT+1 WHERE COMMONUSER_USER_ID in (" + StringUtil.buildArrayToString(theSameList) + ")  AND SY_CREATEUSERID = '" + loginUserId + "' AND SY_CREATEORGID = '" + realOrgId + "'");
            //如果选了两次再次加1
            for (String s : addList) {
                boolean b = set.add(s);
                if (!b) {
                    metaService.executeSql(" UPDATE JE_WORKFLOW_COMMONUSER SET COMMONUSER_COUNT = COMMONUSER_COUNT+1 WHERE COMMONUSER_USER_ID = '" + s + "'  AND SY_CREATEUSERID = '" + loginUserId + "' AND SY_CREATEORGID = '" + realOrgId + "'");
                }
            }
            // 不同人的集合id
            List<String> defferentList = getTheSameSection(idSource, addList, false);
            LinkedHashSet<String> hashSet = new LinkedHashSet<>(defferentList);

            ArrayList<String> listWithoutDuplicates = new ArrayList<>(hashSet);

            // 添加常用人信息
            for (String deptUserId : listWithoutDuplicates) {
                if (deptUserId.equals(RANDOM_TEAM_ID)) {
                    continue;
                }
                DynaBean dynaBean = new DynaBean("JE_WORKFLOW_COMMONUSER", false);
                dynaBean.set("COMMONUSER_COUNT", 1);
                dynaBean.set("COMMONUSER_USER_ID", deptUserId);
                dynaBean.set("COMMONUSER_USER_NAME", addMap.get(deptUserId));
                commonService.buildModelCreateInfo(dynaBean);
                metaService.insert(dynaBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取两个集合中 相同元素和不同元素的集合
     *
     * @param list1 包含集合元素
     * @param list2 被包含集合元素
     * @param flag  如果为true的话返回相同元素  false 返回不同元素
     * @return
     */
    private List getTheSameSection(List<String> list1, List<String> list2, Boolean flag) {
        List theSameList = new ArrayList();
        List diferentList = new ArrayList();
        for (String item : list2) {//遍历list2
            if (list1.contains(item)) {//如果存在这个数
                theSameList.add(item);//放进一个list里面，这个list就是交集
            } else {
                diferentList.add(item);
            }
        }
        if (flag) {
            return theSameList;
        }
        return diferentList;
    }


    @Override
    public Map<String, Object> buildOperationCustomerParam(String operationId, HttpServletRequest request) {
        Map<String, Object> operationCustomerParam = new HashMap<>();
        buildAssigneeInfo(request, operationCustomerParam);
        buildTaskId(request, operationCustomerParam);
        String opinionType = getStringParameter(request, "operationId");
        operationCustomerParam.put("opinionType", opinionType);
        String rebookType = getStringParameter(request, "opinionType");
        operationCustomerParam.put("rebookType", rebookType);
        String comment = getStringParameter(request, "comment");
        operationCustomerParam.put("comment", comment);
        String sequentials = getStringParameter(request, "sequentials");
        operationCustomerParam.put("sequentials", sequentials);
        String isJump = getStringParameter(request, "isJump");
        operationCustomerParam.put("isJump", isJump);
        String signBackId = getStringParameter(request, "signBackId");
        operationCustomerParam.put("signBackId", signBackId);

        //催办参数
        String reminderMethod = getStringParameter(request, "reminderMethod");
        operationCustomerParam.put("reminderMethod", reminderMethod);
        String personBeingUrgedIds = getStringParameter(request, "personBeingUrgedIds");
        operationCustomerParam.put("personBeingUrgedIds", personBeingUrgedIds);
        String personBeingUrgedNames = getStringParameter(request, "personBeingUrgedNames");
        operationCustomerParam.put("personBeingUrgedNames", personBeingUrgedNames);
        String urgentContent = getStringParameter(request, "urgentContent");
        operationCustomerParam.put("urgentContent", urgentContent);
        String ccUserIds = getStringParameter(request, "ccUserIds");
        operationCustomerParam.put("ccUserIds", ccUserIds);
        String ccUserNames = getStringParameter(request, "ccUserNames");
        operationCustomerParam.put("ccUserNames", ccUserNames);
        String ccContent = getStringParameter(request, "ccContent");
        operationCustomerParam.put("ccContent", ccContent);
        String currentNodeId = getStringParameter(request, "currentNodeId");
        operationCustomerParam.put("currentNodeId", currentNodeId);
        String exigency = getStringParameter(request, "exigency");
        operationCustomerParam.put("exigency", exigency);

        return operationCustomerParam;
    }

    /**
     * taskId
     *
     * @param request
     * @param operationCustomerParam
     */
    private void buildTaskId(HttpServletRequest request, Map<String, Object> operationCustomerParam) {
        String taskId = getStringParameter(request, "taskId");
        String piid = getStringParameter(request, "piid");
        operationCustomerParam.put("taskId", taskId);
        operationCustomerParam.put("piid", piid);
    }

    /**
     * 处理人和next节点信息
     *
     * @param request
     * @param operationCustomerParam
     */
    private void buildAssigneeInfo(HttpServletRequest request, Map<String, Object> operationCustomerParam) {
        String assignee = getStringParameter(request, "assignee");
        operationCustomerParam.put("assignee", assignee);
        String target = getStringParameter(request, "target");
        operationCustomerParam.put("target", target);
    }

    /**
     * put自定义参数
     *
     * @param map
     * @param operationCustomerParam
     */
    private void putOperationCustomerParam(Map<String, Object> map, Map<String, Object> operationCustomerParam) {
        for (String key : operationCustomerParam.keySet()) {
            map.put(key, operationCustomerParam.get(key));
        }
    }

    private String getLogUserId() {
        Account account = SecurityUserHolder.getCurrentAccount();
        String userId = "";
        if (account == null) {
            userId = "admin";
        } else {
            userId = account.getDeptId();
        }
        return userId;
    }

//    String getStringParameter(HttpServletRequest request, String key) {
//        if (request.getParameterMap().containsKey(key)) {
//            return request.getParameter(key);
//        } else {
//            return request.getAttribute(key) == null ? null : (String) request.getAttribute(key);
//        }
//    }
}
